<?php
/**

 */
namespace frontend\controllers;

use common\models\Commodity;
use common\models\Gold;
use common\models\RechargeRecord;
use common\models\UserAmount;
use common\models\UserOwned;
use common\models\UserOwnedLog;
use \Yii;
use yii\web\Controller;

use common\models\Order;
//use common\service\BdPush;


class PingXxController extends Controller
{
    public $enableCsrfValidation = false;

    function actionIndex()
    {

        $event = json_decode(file_get_contents("php://input"));
        $event_data = json_decode(file_get_contents("php://input"), true);


        // 对异步通知做处理
        if (!isset($event->type)) {
            header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
            exit("fail");
        }

        if (!isset($event_data['data']) || !isset($event_data['data']['object'])) {
            header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
            exit("fail");
        }

        $input_data = $event_data['data']['object'];

        switch ($event->type) {
            case "charge.succeeded":
                if ($input_data['paid'] == true) {
                    $order_ping = Order::find()->where(['order_ch_id'=>$input_data['id'], 'pay_status' => '待支付'])->asArray()->one();
                    if ($order_ping) {
                        $gold_info = Gold::find()->where(['id'=>$order_ping['goods_id'], 'status'=>'1'])->asArray()->one();
                        if(!$gold_info){
                            echo "商品不存在";
                            die;
                        }
                        $order = new Order();
                        $order->pay_status = '已支付';
                        $order->pay_time   = $input_data['time_paid'];
                        $order->edit_time  = time();
                        if ($order->save()) {
                            $param['user_id'] = $order_ping['user_id'];
                            $param['operate_cnt'] = $gold_info['number'];
                            $param['operate'] = 1;
                            $param['operate_name'] = '充值';
                            UserAmount::addUserAmount($param);
                        } else {
                            echo "修改订单状态失败";
                        }
                    } else {
                        echo "订单不存在";
                        die;
                    }
                } else {
                    echo "返回值有误";
                }
                break;
            default:
                header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
                break;
        }
    }
}
